/*
 * Copyright 2002-present the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.graphql.server.webflux;

import java.net.URI;

import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;

import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.web.reactive.socket.CloseStatus;
import org.springframework.web.reactive.socket.HandshakeInfo;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.adapter.AbstractWebSocketSession;

/**
 * {@link org.springframework.web.reactive.socket.WebSocketSession} that is given an input
 * Flux of messages and exposes a Flux of published output messages.
 */
class TestWebSocketSession extends AbstractWebSocketSession<Object> {

	private final Flux<WebSocketMessage> input;

	private Flux<WebSocketMessage> output = Flux.empty();

	private final Sinks.One<CloseStatus> closeStatusSink = Sinks.one();

	TestWebSocketSession(Flux<WebSocketMessage> input) {
		this("1", URI.create("https://example.org/graphql"), input);
	}

	TestWebSocketSession(String id, URI uri, Flux<WebSocketMessage> input) {
		super(new Object(), id, new HandshakeInfo(uri, new HttpHeaders(), Mono.empty(), null),
				DefaultDataBufferFactory.sharedInstance);
		this.input = input;
	}

	@Override
	public Flux<WebSocketMessage> receive() {
		return this.input;
	}

	@Override
	public Mono<Void> send(Publisher<WebSocketMessage> messages) {
		this.output = Flux.from(messages);
		return Mono.empty();
	}

	Flux<WebSocketMessage> getOutput() {
		return this.output;
	}

	@Override
	public boolean isOpen() {
		throw new UnsupportedOperationException();
	}

	@Override
	public Mono<Void> close(CloseStatus status) {
		this.closeStatusSink.tryEmitValue(status);
		return Mono.empty();
	}

	@Override
	public Mono<CloseStatus> closeStatus() {
		return this.closeStatusSink.asMono();
	}

}
